package com.vpen.blog.utils;

import com.vpen.blog.config.security.JwtTokenUtils;
import com.vpen.blog.entity.Blog;
import com.vpen.blog.entity.User;
import com.vpen.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * -@Version 1.0
 * -@Author:Vpen
 * -@Date:2021/7/12 13:41
 * -@Content:
 */
@Component
public class BlogUtils {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private  UserService userService;
//
    // 配置文件里有写
    @Value("${jwt.tokenHead}")
    private  String tokenHead;
    // 前端存在Session中的token的key
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

//    // 将传来的文章数据封装
    public  Blog encodeBlog(Map<String,Object> article){
        Blog blog = new Blog();
        String title = (String) article.get("title");
        String content = (String) article.get("content");
        Long id = (Long) article.get("userId");
        blog.setTitle(title);
        blog.setContent(content);
        blog.setCreated(LocalDateTime.now());// 获取当前时间
        blog.setUserId(id);
        blog.setStatus(1);// 0 是草稿， 1 是已经发表成功
        return blog;
    }
//
//

//    // 传来的文章，我需要从头部获取token解析得到用户名，找到用户的id就是谁写的这编文章
    public  Long getUserId(HttpServletRequest request){
        String tokenStr = request.getHeader(tokenHeader);
        String token = parseToken(tokenStr);
        if (token != null) {
            String name = jwtTokenUtils.getUserNameFromToken(token);
            User user = userService.getUserByUserName(name);
            return user.getId();
        }
        return null;
    }
//    // 解析token
    private   String parseToken(String tokenStr){
        if (tokenStr!=null && tokenStr.startsWith(tokenHead)){
            return tokenStr.substring(tokenHead.length());
        }
        return null;
    }
}
